package cn.dw.mm.service.impl;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Iterator;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import cn.dw.mm.service.FileService;
import cn.dw.mm.utils.FileUtils;

@Service
public class FileServiceImpl implements FileService{

	@Override
	public int download(String fileDir, String fileName, HttpServletRequest req, HttpServletResponse resp) throws IOException {
    	//先判断特定目录底下是否存在同名的文件
    	File file = null;
    	File[] matchFiles = FileUtils.searchFile(new File(fileDir), fileName);
    	if (matchFiles.length == 1) {
			file = matchFiles[0];
			FileInputStream fileIn = new FileInputStream(file);
	    	resp.setContentType("application/x-msdownload;");
	    	resp.setHeader("Content-disposition", "attachment; filename="+file.getName());
	    	resp.setHeader("Content-Length", String.valueOf(file.length()));
	    	OutputStream out= resp.getOutputStream();
	    	byte[] buf = new byte[1024];
	    	while((fileIn.read(buf)) > 0) {
	    		out.write(buf);
	    	}
	    	out.flush();
	    	out.close();
	    	fileIn.close();
	    	return 1;
		} else {
			return -1;
		}
	}
}
